package com.easycms.web.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.easycms.common.LoggerHelper;
import com.easycms.constant.CookieConstants;
import com.easycms.framework.domain.ResultAdaptDto;
import com.easycms.enums.DataStatusEnum;
import com.easycms.framework.exception.EasyException;
import com.easycms.framework.properties.EasyCmsConfig;
import com.easycms.framework.shiro.UserOwnInfo;
import com.easycms.framework.web.ActionResult;
import com.easycms.framework.web.BaseController;
import com.easycms.framework.web.RequestHelper;
import com.easycms.web.system.domain.SysRole;
import com.easycms.web.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.easycms.web.system.service.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController extends BaseController {
    private  String DesKey = "#s^un2ye21fcv%|f0XpR,+vh";
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private RequestHelper requestHelper;
    @Autowired
    private EasyCmsConfig easyCmsConfig;
    @GetMapping("/login")
    public ActionResult Index(Model model){

        model.addAttribute("projectName",easyCmsConfig.getName());
        model.addAttribute("copyrightYear", DateUtil.date().year());
        return view("/home/login");
    }


    @PostMapping("/loginOn")
    public ActionResult LoginOn(String username, String password, HttpServletResponse response){
        ResultAdaptDto result=new ResultAdaptDto();
        result.getData().put("username",username);
        result.getData().put("password", password);
        if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            return error("用户名或者密码不能为空");
        }

        SysUser user=userService.login(username.trim());

        if(user==null){
           return error(StrUtil.format("用户:[{}]不存在",username));
        }
        if(user.getUserStatus().equals(DataStatusEnum.DISABLE.getCode())){
            return error(StrUtil.format("用户:[{}]已禁用",username));
        }
        if(!user.getPassWord().equals(password)){
            return error(StrUtil.format("用户:[{}]密码错误",username));
        }

        UserOwnInfo userOwnInfo=new UserOwnInfo();
        BeanUtil.copyProperties(user, userOwnInfo);
        userOwnInfo.setDeptName(user.getDeptName());
        if(user.getRoleId()>0){
            SysRole role=roleService.getModel(user.getRoleId());
            if(role!=null){
                userOwnInfo.setRoleName(role.getRoleName());
                userOwnInfo.setRoleCode(role.getRoleCode());
            }
        }
        if(user.getIsSuper()==DataStatusEnum.SUPER.getCode()){
            userOwnInfo.setAdmin(true);
        }
        String jsonString=JSONUtil.toJsonStr(userOwnInfo);
        //LoggerHelper.console("登录："+jsonString);

        try {
            String cookieUserVal= URLEncoder.encode(jsonString, "UTF-8");
            Cookie userCookie = new Cookie(CookieConstants.LOGIN_COOKIE_NAME, cookieUserVal);

            userCookie.setMaxAge(30 * 24 * 60 * 60);
            userCookie.setPath(requestHelper.getContextPath());
            // 使用 HttpServletResponse 对象向客户端发送 Cookie
            response.addCookie(userCookie);
        } catch (UnsupportedEncodingException e) {
            LoggerHelper.error(e.getMessage());
        }

        result.put("url","/home/index");
        result.setMessage("登录成功");
        return json(result);
        //return ok("登录成功");
    }

    @GetMapping("/logout")
    public ActionResult  loginOut( HttpServletResponse response){

        Cookie userCookie = new Cookie(CookieConstants.LOGIN_COOKIE_NAME, null);
        userCookie.setMaxAge(0);
        response.addCookie(userCookie);
        return redirectTo("/login");
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }

}
